package com.xinyue.chat.netty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class DecodeHandler extends ChannelInboundHandlerAdapter {
	private Logger logger = LoggerFactory.getLogger(DecodeHandler.class);

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info("客户端连接成功");
		ctx.fireChannelActive();
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf byteBuf = (ByteBuf) msg;

		int messageLength = byteBuf.readInt();
		int seqId = byteBuf.readInt();
		int messageId = byteBuf.readInt();
		int messageType = byteBuf.readByte();
		long clientSendTime = byteBuf.readLong();
		int bodyLength = byteBuf.readableBytes();// 剩下的都是包体的字节长度
		JSONObject body = null;
		if (bodyLength > 0) {
			byte[] bodyBytes = new byte[bodyLength];
			byteBuf.readBytes(bodyBytes);
			String json = new String(bodyBytes);
			body = JSONObject.parseObject(json);
		}

		MessageRequest messagePackage = new MessageRequest();
		MessageHeader header = new MessageHeader();
		header.setClientSendTime(clientSendTime);
		header.setMessageId(messageId);
		header.setSeqId(seqId);
		header.setMessageType(messageType);
		header.setMessageLength(messageLength);
		messagePackage.setHeader(header);
		messagePackage.setBody(body);
		ctx.fireChannelRead(messagePackage);

	}
}
